const { google } = require("googleapis");
const fs = require("fs");
const path = require("path");
const config = require("../config");
const scopes = ["https://www.googleapis.com/auth/androidpublisher"];

async function androidPublisherConn(packageName) {
    try {
        let keyPath = ""; // JSON密钥文件的路径
        const operatingSystem = process.platform;
        // 根据不同的操作系统和包名设置密钥文件的路径
        if (operatingSystem.includes("win")) {
            keyPath = path.join(__dirname, '../static/ins2_json_key.json');
        } else if (operatingSystem === "linux" || operatingSystem === "darwin") {
            switch (packageName) {
                case config.INS1:
                    keyPath = '/zj-manager/zj-background-manager/json_key.json';
                    break;
                case config.INS2:
                case config.ALL:
                case config.ALL2:
                case config.androidRoku2:
                case config.androidRoku3:
                case config.androidCalorie:
                case config.androidPrint:
                case config.androidQr:
                    keyPath = '/zj-manager/zj-background-manager/ins2_json_key.json';
                    break;
                case config.PDF:
                case config.INS3:
                case config.STEPCOUNTER:
                case config.WA2:
                case config.WA3:
                    keyPath = '/zj-manager/zj-background-manager/pdf_wamr_counter_json_key.json';
                    break;
                case config.CALCULATOR:
                    keyPath = '/zj-manager/zj-background-manager/calculator_json_key.json';
                    break;
                case config.CHAT1:
                case config.CHAT2:
                case config.CHAT5:
                case config.androidSamsung:
                case config.androidRoku:
                case config.androidLG:
                case config.androidFiretv:
                    keyPath = '/zj-manager/zj-background-manager/chat_ai_json_key.json';
                    break;
                default:
                    console.info("Package name does not match any known keys");
                    return null;
            }
        } else {
            throw new Error("无法确定当前环境");
        }

        if (!fs.existsSync(keyPath)) {
            throw new Error(`Key file not found at: ${keyPath}`);
        }


        const auth = new google.auth.GoogleAuth({
            keyFile: keyPath,
            scopes: scopes,
        });

        const authClient = await auth.getClient();

        const androidpublisher = google.androidpublisher({
            version: "v3",
            auth: authClient,
        });

        return androidpublisher;
    } catch (error) {
        console.error(error);
        return null;
    }
}
module.exports = androidPublisherConn;
